package com.home.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.home.biz.ActivityBiz;
import com.home.biz.LtPhoneBiz;
import com.home.entity.ActivityPhone;
import com.home.entity.LtPhone;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;

/**
 * @author ：chenxf
 * @date ：Created in 2020/6/10 12:45
 * @description：
 * @modified By：
 * @version: $
 */
@Slf4j
public class FetchLtUtil implements Callable<String> {

    private LtPhoneBiz activityBiz;
    /**
     * C002
     * 2003130012433867 -- 一生一号
     * 1910170012348890 --  靓号
     * 1910170012348890 -- 4G飞享18元档
     * 1910230012354413 -- 4G飞享（分销）18元档
     */
    String param="queryPara=#NUM&orderId=#TIME61&queryType=07&qrCodeId=e5af19d2c0594f84b0b2a6779d8903bb&specialIds=1T71T75";
    String  provName="", cityName="",data="",activiName="";
    String url="https://mall.cqwin.com/shopCenter/shopOrder/tverify/simpsnresQry";
    String tokenCode="58j318lpb38dlds340099bj0r4b1b8p9";
    DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
    public FetchLtUtil(String data){
        this.data=data;

    }
    public FetchLtUtil(LtPhoneBiz activityBiz, String activiName, String num){
        //20200610121240
        this.data=param.replace("#NUM",num).replace("#TIME",formatter.format(LocalDateTime.now()));
        this.activityBiz=activityBiz;
//        this.provName=provName;
//        this.cityName=cityName;
        // this.acitviCode=acitviCode;
        this.activiName=activiName;
    }


    public void save() {

        try {
            int times=0;
            while (times<3){
                List<LtPhone> result=fetch();
                if(result!=null){
                    activityBiz.saveList(result);
                    break;
                }
                times++;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<LtPhone> fetch() throws Exception {
        log.debug("fetch data"+data);
        String userDir = System.getProperty("user.dir");
        //String classesPath=Thread.currentThread().getContextClassLoader().getResource("").getPath().substring(1);
        log.debug("userDirt={}",userDir);

       // String home = userDir.substring(0, userDir.lastIndexOf('/'));
        System.setProperty("javax.net.ssl.trustStore", userDir+"/lt.jks");
        String doc = Jsoup.connect(url+"?"+data)
                .ignoreContentType(true)

                .method(Connection.Method.POST)
                .header("Content-Type","application/json;charset=UTF-8")
                .header("tokenCode",tokenCode)
               // .userAgent("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)")
                // .cookies(cookie)
                .execute()
                .body();
        JSONObject obj= JSON.parseObject(doc);
        log.debug("obj={}",obj);
        String result=obj.getString("code");
        if("1".equals(result)){
            log.debug("fetch finished");
            List<Map> list=JSON.parseArray(obj.getJSONArray("numInfo").toJSONString(),Map.class);

            return  list.stream().map(m->LtPhone.builder().phoneNum(m.get("numId").toString()).provName(m.get("advancePay").toString()).cityName(m.get("lowCostPro").toString()).fetchMethod(activiName).build()).collect(Collectors.toList());

        }else {
            log.error("采集异常");
        }
        return null;
    }

    @Override
    public String call() throws Exception {
        save();
        return data+"fetch finish";
    }

    public static void main(String[] args){

        FetchLtUtil fetchNumUtil=new FetchLtUtil( "queryPara=122&orderId=2020061012124036161&queryType=07&qrCodeId=e5af19d2c0594f84b0b2a6779d8903bb&specialIds=1T71T75");
        try {
            List<LtPhone> result=fetchNumUtil.fetch();
            System.out.println(result.size());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
